# app/config/settings.py

import os
from pathlib import Path
ALLOWED_HOSTS = ['localhost', '127.0.0.1']

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'your-very-secure-secret-key'
DEBUG=True

MIDDLEWARE = [
    # 必须的中间件
    'django.middleware.security.SecurityMiddleware',  # 安全中间件
    'django.contrib.sessions.middleware.SessionMiddleware',  # 会话中间件
    'django.contrib.auth.middleware.AuthenticationMiddleware',  # 认证中间件
    'django.contrib.messages.middleware.MessageMiddleware',  # 消息中间件
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',  # CSRF 防护中间件
    'django.middleware.clickjacking.XFrameOptionsMiddleware',  # 防止点击劫持
]

INSTALLED_APPS = [
    # Django 默认应用
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    # 第三方库
    'rest_framework',
    'rest_framework.authtoken',
    'rest_framework_simplejwt',
    'corsheaders',
    'channels',
    
    # 我们的应用模块
    'apps.core',
    'apps.monitoring',
    'apps.control',
    'apps.rooms',
    'apps.devices',
    'apps.users',
    'apps.user_device_map',
    'apps.video_records',
    'apps.alert',
]

# 数据库配置（MySQL）
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'smart_home_system',  # 数据库名称
        'USER': 'root',  # MySQL 用户名
        'PASSWORD': '123456',  # MySQL 密码
        'HOST': 'localhost',  # MySQL 主机地址（如果在 Docker 中运行，使用容器名）
        'PORT': '3307',  # MySQL 端口
    }
}

# JWT认证
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20
}

# ASGI配置
ASGI_APPLICATION = 'config.asgi.application'

# 通道层（Redis）
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],  # Redis 地址
        },
    },
}

# InfluxDB配置
INFLUXDB_URL = "http://localhost:8086"  # InfluxDB 地址
INFLUXDB_TOKEN = "your_influxdb_admin_password"  # InfluxDB 管理员密码
INFLUXDB_ORG = "smart_home"  # InfluxDB 组织
INFLUXDB_BUCKET = "sensor_data"  # 数据库桶

# 项目根URL配置
ROOT_URLCONF = 'config.urls'

# 模板配置
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# 静态文件配置
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]  # 你的静态文件目录
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')  # 生产环境收集用

# 媒体文件配置
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

# 国际化
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = True

# 认证后端
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
]

# CORS配置
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",  # React开发服务器
    "http://127.0.0.1:3000",
]

# JWT配置
from datetime import timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': True,
}

# 安全配置（生产环境需要）
SECURE_SSL_REDIRECT = False  # 生产环境应设为True
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
